<?php
namespace App\Controller;
/**
 * “我为西恩续一秒”春季赛活动
 * @author liubo <liubo@ilongyuan.com.cn>
 */
class CndotaController extends AppController
{
    private $score = 300;
    public function _initialize() {
        exit('活动已结束');//2016-06-13 by liubo
        parent::_initialize();
        $this->matchId = 25;// 正式服
    }

    public function index()
    {
        setRedirect();

        $referral = I('referral', '');
        $referral && $refuser = event('User')->getByRefer($referral);
        if ($refuser) {
            session('_cndota_referral_uid', $refuser['id']);
        }

        $this->assign('user',$this->user);

        // 第一部分
        $this->assign('curCount', $this->_curCount());
        $this->assign('giftList', $this->_gift());
        $this->assign('a1s', intval($this->_today_a1s()));

        // 第二部分
        $map['uid'] = UID;
        $map['team_id'] = ['$ne' => null]; // team_id不为空时，是预测数据
        $forecast = service('Cndota/CndotaData')->where($map)->find();
        $this->assign('teamList', $this->_team());
        $this->assign('forecast', $forecast?$forecast['team_id']:0);

        // 第三部分
        $this->assign('matchId',$this->matchId);
        $races = $this->_races();
        $this->assign('raceList', $races);
        $this->assign('raceId', $races[0]['races'][0]);

        $this->assign('title', '我为西恩续一秒');

        if (IS_MOBILE) {
            return $this->display('mobile');
        }
        $this->display('cndota');
    }

    /**
     * 预测
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function forecast() {
        if (!UID) {
            $this->ajaxReturn(['state' => -2, 'info' => '未登录']);
        }
        $team_id = I('team_id', 0, 'intval');
        if ($team_id) {
            $team = service('Cndota/CndotaTeam')->find($team_id);
            !$team && $this->ajaxReturn(['state' => -1, 'info' => '参数不正确']);
        } else {
            $this->ajaxReturn(['state' => -1, 'info' => '参数不正确']);
        }

        $serviceObj = service('Cndota/CndotaData');

        $map['uid'] = UID;
        $map['team_id'] = ['$ne' => null]; // team_id不为空时，是预测数据
        $info = $serviceObj->where($map)->find();

        if ($info) {
            $this->ajaxReturn(['state' => -1, 'info' => '只能预测一次']);
        }


        $data = ['uid' => UID, 'team_id' => $team_id];
        $referral_uid = session('_cndota_referral_uid');
        if ($referral_uid) {
            $data['referral_uid'] = $referral_uid;
            $scoreOperCount = $this->_today_score_count($referral_uid);
            if ($scoreOperCount < 10) {
                //TODO 分享增加积分
                event('User')->score_oper($referral_uid, $this->score, 'cndota_share');
            }
        }

        $serviceObj->create($data);
        $res = $serviceObj->add();

        if(!$res) {
            $this->ajaxReturn(['state' => -1, 'info' => '预测失败']);
        }

        $this->ajaxReturn(['state' => 0, 'info' => '预测成功']);
    }

    /**
     * 加一秒
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function a1s() {
        if (!UID) {
            $this->ajaxReturn(['state' => -2, 'info' => '未登录']);
        }

        $info = $this->_today_a1s();
        if ($info) {
            $this->ajaxReturn(['state' => -1, 'info' => '每天只有一次机会']);
        }
        $data = ['uid' => UID];
        $referral_uid = session('_cndota_referral_uid');
        if ($referral_uid) {
            $data['referral_uid'] = $referral_uid;
            $scoreOperCount = $this->_today_score_count($referral_uid);
            if ($scoreOperCount < 10) {
                //TODO 分享增加积分
                event('User')->score_oper($referral_uid, $this->score, 'cndota_share');
            }
        }

        $serviceObj = service('Cndota/CndotaData');
        $serviceObj->create($data);
        $res = $serviceObj->add();
        if(!$res) {
            $this->ajaxReturn(['state' => -1, 'info' => '操作失败']);
        }
        $this->ajaxReturn(['state' => 0, 'info' => '操作成功']);
    }

    /**
     * 奖品
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _gift() {
        $serviceObj = service('Cndota/CndotaGift');
        $list = $serviceObj->field('name,unlockcount,logo,video_id')->order('unlockcount asc')->select();
        $data = [];
        foreach ($list as $value) {
            uri_format($value['logo']);
            if (IS_MOBILE) {
                $video = event('Video')->detail($value['video_id']);
                $value['video_uri'] = $video['uri'];
            }
            $data[] = $value;
        }
        return $data;
    }
    /**
     * 队伍
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _team() {
        $serviceObj = service('Cndota/CndotaTeam');
        $field = 'name,shortname,description,logo,cover,id';
        $list = $serviceObj->field($field)->order('id asc')->select();
        $data = [];
        $dataServiceObj = service('Cndota/CndotaData');
        foreach ($list as $value) {
            uri_format($value['logo']);
            uri_format($value['cover']);

            $value['count'] = $dataServiceObj->where(['team_id' => $value['id']])->count();

            $data[] = $value;
        }
        return $data;
    }

    private function _today_a1s() {
        $serviceObj = service('Cndota/CndotaData');
        //查询今天是否操作过
        $map['uid'] = UID;
        $map['team_id'] = ['$eq' => null]; //team_id为空时，为加一秒数据
        $start = strtotime(date('Y-m-d'));
        $end = $start + 24*60*60;
        $map['create_time'] = ['$gte' => $start, '$lt' => $end];

        $info = $serviceObj->where($map)->find();
        return !empty($info);
    }

    /**
     * 今天加积分次数
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _today_score_count($uid) {
        $serviceObj = service('Cndota/CndotaData');

        $map['referral_uid'] = $uid;
        $start = strtotime(date('Y-m-d'));
        $end = $start + 24*60*60;
        $map['create_time'] = ['$gte' => $start, '$lt' => $end];
        $count = $serviceObj->where($map)->count();
        return $count;
    }

    /**
     * 当前“续一秒”数量
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    private function _curCount() {
        $serviceObj = service('Cndota/CndotaData');
        $map['team_id'] = ['$eq' => null];
        $count = $serviceObj->where($map)->count();
        return $count;
    }

    private function _races() {
        $eventObj = A('Api/match', 'Event');
        $videoEvent = A('Api/Video', 'Event');

        $match = $eventObj->info($this->matchId);
        $p = 1;
        $pager = 4;
        if (IS_MOBILE) {
            $pager = 10;
        }

        $rgEventObj = A('Api/RaceGroup', 'Event');

        $map = array(
                'match_id'=>$this->matchId, 
                'state'=>1,
                //TODO 6.6-6.12
                // 'race_date'=>array('in', $raceDates)
                );
        $ids = $rgEventObj->lists($map, 'id', $pager, $p, 'race_time desc');
        $data = [];
        $fieldMap = ['id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team'];
        foreach ($ids as $value) {
            $detail = $rgEventObj->info($value['id'], $match['teamlogo']);
            $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
            $detail = $this->field_filter($detail, $fieldMap);

            $races = $videoEvent->lists(['group_id' => $detail['id'], 'type' => 1], 3, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
            }
            $detail['races'] = $races;
            $data[] = $detail;
        }
        return $data;
    }
}